package com.vip8.recorder.service.service.impl;

import com.vip8.recorder.api.model.base.MultiResult;
import com.vip8.recorder.api.model.dto.KeyPointDTO;
import com.vip8.recorder.api.model.dto.RecorderDTO;
import com.vip8.recorder.api.model.params.KeyPointParams;
import com.vip8.recorder.api.model.params.VideoParams;
import com.vip8.recorder.service.db.mapper.RecorderInfoDao;
import com.vip8.recorder.service.db.mapper.RecorderKeyPointDao;
import com.vip8.recorder.service.db.model.RecorderInfo;
import com.vip8.recorder.service.db.model.RecorderInfoExample;
import com.vip8.recorder.service.db.model.RecorderKeyPoint;
import com.vip8.recorder.service.db.model.RecorderKeyPointExample;
import com.vip8.recorder.service.service.OssManageService;
import com.vip8.recorder.service.service.RecorderService;
import com.vip8.recorder.service.utils.BeanCopyUtil;
import com.vip8.recorder.service.utils.CollectionUtil;
import com.vip8.recorder.service.utils.JsonUtil;
import com.vip8.recorder.service.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
;

@Service
@Slf4j
public class RecorderServiceImpl implements RecorderService {
    @Resource
    private RecorderInfoDao recorderInfoDao;
    @Resource
    private RecorderKeyPointDao keyPointDao;
    @Resource
    private OssManageService ossManageService;

    @Override
    public boolean uploadVideo(VideoParams videoParams) {

        if (!ossManageService.isExits(videoParams.getVideoFileKey())) {
            throw new RuntimeException("视频fileKey不存在" + videoParams.getVideoFileKey());
        }
        RecorderInfo recorder = new RecorderInfo();
        BeanCopyUtil.copyBean(videoParams, recorder);
        RecorderInfoExample example = new RecorderInfoExample();
        example.createCriteria().andVideoIdEqualTo(videoParams.getVideoId());
        List<RecorderInfo> recorderInfos = recorderInfoDao.selectByExample(example);
        if (CollectionUtil.isEmpty(recorderInfos)) {
            recorderInfoDao.insertSelective(recorder);
        } else {
            recorderInfoDao.updateByExampleSelective(recorder, example);
        }
        return true;
    }

    @Override
    public boolean markVideo(KeyPointParams params) {
        RecorderKeyPoint keyPoint = new RecorderKeyPoint();
        RecorderKeyPointExample example = new RecorderKeyPointExample();

        RecorderKeyPointExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(params.getVideoId())) {
            criteria.andVideoIdEqualTo(params.getVideoId());
        }
        if (params.getKeyPoint() != null) {
            criteria.andKeyPointEqualTo(params.getKeyPoint());
        }
        BeanCopyUtil.copyBean(params, keyPoint);
        List<RecorderKeyPoint> keyPoints = keyPointDao.selectByExample(example);
        if (CollectionUtil.isEmpty(keyPoints)) {
            keyPointDao.insertSelective(keyPoint);
        } else {
            log.info("markVideo: has record " + JsonUtil.toJsonString(params));
        }
        return true;
    }

    @Override
    public MultiResult<RecorderDTO>  queryRecorderHome(VideoParams queryParams) {
        RecorderInfoExample example = new RecorderInfoExample();
        RecorderInfoExample.Criteria criteria = example.createCriteria();
        if (queryParams.getStartTime() != null && queryParams.getEndTime() != null) {
            criteria.andStartTimeBetween(queryParams.getStartTime(), queryParams.getEndTime());
        }
        if (StringUtil.isNotEmpty(queryParams.getStartCity())) {
            criteria.andStartCityLike("%" + queryParams.getStartCity() + "%");
        }
        if (StringUtil.isNotEmpty(queryParams.getPhone())) {
            criteria.andPhoneEqualTo(queryParams.getPhone());
        }
        if(CollectionUtil.isNotEmpty(queryParams.getPhoneList())){
            criteria.andPhoneIn(queryParams.getPhoneList());
        }
        if(StringUtil.isNotEmpty(queryParams.getEmployeeId())){
            criteria.andEmployeeIdEqualTo(queryParams.getEmployeeId());
        }
        if (StringUtil.isNotEmpty(queryParams.getEmpName())) {
            criteria.andEmpNameLike("%"+ queryParams.getEmpName() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getScene())){
            criteria.andSceneLike("%"+ queryParams.getScene() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getPartner())){
            criteria.andPartnerLike("%"+ queryParams.getPartner() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getSupplier())){
            criteria.andSupplierLike("%"+ queryParams.getSupplier() + "%");
        }
        int offset = 0;
        if (queryParams.getStartPage() != null) {
            offset = queryParams.getStartPage() < 1 ? 0 : (queryParams.getStartPage() - 1) * queryParams.getPageSize();
        }
        example.setOffset((long) offset);
        example.setLimit(queryParams.getPageSize());
        long total = recorderInfoDao.countByRecorder(example);

        List<RecorderInfo> recorderInfos=  recorderInfoDao.selectUserInfoByRecorder(example);
        List<RecorderDTO> recorderDTOS = null;
        if (CollectionUtil.isNotEmpty(recorderInfos)) {
            recorderDTOS =  recorderInfos.stream().map((item -> {
                RecorderDTO recorderDTO = new RecorderDTO();
                BeanCopyUtil.copyBean(item, recorderDTO);
                if (StringUtil.isNotEmpty(item.getVideoFileKey())) {
                    String url = ossManageService.getUrlByFileKey(item.getVideoFileKey());
                    recorderDTO.setVideoUrl(url);
                }
                if(StringUtil.isNotEmpty(item.getCoverFileKey())){
                    String url = ossManageService.getUrlByFileKey(item.getCoverFileKey());
                    recorderDTO.setCoverUrl(url);
                }
                return recorderDTO;
            })).collect(Collectors.toList());
        }
        return  MultiResult.success(recorderDTOS, (int) total);
    }

    @Override
    public List<RecorderDTO> exportRecorders(VideoParams queryParams) {
        RecorderInfoExample example = new RecorderInfoExample();
        RecorderInfoExample.Criteria criteria = example.createCriteria();
        if (queryParams.getStartTime() != null && queryParams.getEndTime() != null) {
            criteria.andStartTimeBetween(queryParams.getStartTime(), queryParams.getEndTime());
        }
        int offset = 0;
        if (queryParams.getStartPage() != null) {
            offset = queryParams.getStartPage() < 1 ? 0 : (queryParams.getStartPage() - 1) * queryParams.getPageSize();
        }
        example.setOffset((long) offset);
        example.setLimit(queryParams.getPageSize());
        List<RecorderInfo> recorders = recorderInfoDao.selectByExample(example);
        if (CollectionUtil.isNotEmpty(recorders)) {
            return recorders.stream().map((item -> {
                RecorderDTO recorderDTO = new RecorderDTO();
                BeanCopyUtil.copyBean(item, recorderDTO);
                if (StringUtil.isNotEmpty(item.getVideoFileKey())) {
                    String url = ossManageService.getUrlByFileKey(item.getVideoFileKey());
                    recorderDTO.setVideoUrl(url);
                }
                if(StringUtil.isNotEmpty(item.getCoverFileKey())){
                    String url = ossManageService.getUrlByFileKey(item.getCoverFileKey());
                    recorderDTO.setCoverUrl(url);
                }
                return recorderDTO;
            })).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public MultiResult<RecorderDTO> queryRecorderList(VideoParams queryParams) {
        RecorderInfoExample example1 = new RecorderInfoExample();
        RecorderInfoExample.Criteria criteria1 = example1.createCriteria();
        if (queryParams.getStartTime() != null && queryParams.getEndTime() != null) {
            criteria1.andStartTimeBetween(queryParams.getStartTime(), queryParams.getEndTime());
        }
        if (StringUtil.isNotEmpty(queryParams.getStartCity())) {
            criteria1.andStartCityLike("%" + queryParams.getStartCity() + "%");
        }
        if (StringUtil.isNotEmpty(queryParams.getPhone())) {
            criteria1.andPhoneEqualTo(queryParams.getPhone());
        }
        if(CollectionUtil.isNotEmpty(queryParams.getPhoneList())){
            criteria1.andPhoneIn(queryParams.getPhoneList());
        }
        if(StringUtil.isNotEmpty(queryParams.getEmployeeId())){
            criteria1.andEmployeeIdEqualTo(queryParams.getEmployeeId());
        }
        if (StringUtil.isNotEmpty(queryParams.getEmpName())) {
            criteria1.andEmpNameLike("%"+ queryParams.getEmpName() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getScene())){
            criteria1.andSceneLike("%"+ queryParams.getScene() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getPartner())){
            criteria1.andPartnerLike("%"+ queryParams.getPartner() + "%");
        }
        if(StringUtil.isNotEmpty(queryParams.getSupplier())){
            criteria1.andSupplierLike("%"+ queryParams.getSupplier() + "%");
        }
        int offset = 0;
        if (queryParams.getStartPage() != null) {
            offset = queryParams.getStartPage() < 1 ? 0 : (queryParams.getStartPage() - 1) * queryParams.getPageSize();
        }
        long total = recorderInfoDao.countByExample(example1);
        example1.setOffset((long) offset);
        example1.setLimit(queryParams.getPageSize());
        example1.setOrderByClause("start_time desc");
        List<RecorderInfo> recorderInfos = recorderInfoDao.selectByExample(example1);
        List<RecorderDTO> recorderDTOS = null;
        if (CollectionUtil.isNotEmpty(recorderInfos)) {
            List<String> videoIds = recorderInfos.stream().map(RecorderInfo::getVideoId).collect(Collectors.toList());
            Map<String, List<KeyPointDTO>> keyPointsMap = getKeyPoints(videoIds);
            recorderDTOS = recorderInfos.stream().map((item -> {
                RecorderDTO recorderDTO = new RecorderDTO();
                BeanCopyUtil.copyBean(item, recorderDTO);
                if (StringUtil.isNotEmpty(item.getVideoFileKey())) {
                    String url = ossManageService.getUrlByFileKey(item.getVideoFileKey());
                    recorderDTO.setVideoUrl(url);
                }
                if(StringUtil.isNotEmpty(item.getCoverFileKey())){
                    String url = ossManageService.getUrlByFileKey(item.getCoverFileKey());
                    recorderDTO.setCoverUrl(url);
                }
                List<KeyPointDTO> keyPointDTOS = keyPointsMap.get(item.getVideoId());
                recorderDTO.setKeyPointList(keyPointDTOS);
                return recorderDTO;
            })).collect(Collectors.toList());
        }
        return  MultiResult.success(recorderDTOS, (int) total);
    }

    /**
     * 批量获取
     *
     * @param videoIds
     * @return
     */
    private Map<String, List<KeyPointDTO>> getKeyPoints(List<String> videoIds) {
        Map<String, List<KeyPointDTO>> keyPointsMap = new HashMap<>();
        if (CollectionUtil.isEmpty(videoIds)) {
            return keyPointsMap;
        }
        RecorderKeyPointExample example = new RecorderKeyPointExample();
        RecorderKeyPointExample.Criteria criteria = example.createCriteria();
        criteria.andVideoIdIn(videoIds);
        List<RecorderKeyPoint> keyPoints = keyPointDao.selectByExample(example);
        if (CollectionUtil.isNotEmpty(keyPoints)) {
            keyPoints.forEach(item -> {
                List<KeyPointDTO> keyPointDTOS;
                if (keyPointsMap.containsKey(item.getVideoId())) {
                    keyPointDTOS = keyPointsMap.get(item.getVideoId());
                } else {
                    keyPointDTOS = new ArrayList<>();
                }
                keyPointDTOS.add(convertToKeyPointDTO(item));
                keyPointsMap.put(item.getVideoId(), keyPointDTOS);
            });
        }
        return keyPointsMap;

    }

    private KeyPointDTO convertToKeyPointDTO(RecorderKeyPoint keyPoint) {
        KeyPointDTO keyPointDTO = new KeyPointDTO();
        BeanCopyUtil.copyBean(keyPoint, keyPointDTO);
        return keyPointDTO;
    }
}
